package com.hyou.sc.eureka.client.auth.module.user;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.hyou.sc.eureka.client.auth.consts.UserStatus;
import com.hyou.sc.eureka.client.auth.dto.form.UserForm;
import com.hyou.sc.eureka.client.auth.dto.pojo.UserDO;
import com.hyou.sc.eureka.client.auth.service.base.itfc.UserService;
import com.hyou.springboot.annotation.FormValidator;
import com.hyou.springboot.base.ResponseMessage;
import com.hyou.springboot.util.BeanCopyUtil;
import com.hyou.springboot.util.ResponseMessageUtil;
import com.hyou.springboot.validator.group.AddGroup;

/**
 * 
 * @author FengChangshuo
 * @version 1.0.0 2018-04-27 15:02:53 初始创建
 */
@RestController("userAddController")
public class UserAddController {
    
    private static final Logger log = LoggerFactory.getLogger(UserAddController.class);
    
    @Resource(name = "userService")
    private UserService userService;
    
    @FormValidator(AddGroup.class)
    @PostMapping(path = "/user/add", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseMessage<Serializable> add(@RequestBody UserForm form) {
        log.debug("param : form : {}", form);
        
        UserDO userDO = new UserDO();
        BeanCopyUtil.copyFormObject(form, userDO);
        userDO.setStatus(UserStatus.ON);
        
        String accountToSign = form.getAccount() + form.getPasswd();
        String md5Pwd = DigestUtils.md5DigestAsHex(accountToSign.getBytes(StandardCharsets.UTF_8));
        userDO.setPasswd(md5Pwd);
        
        Long newId = userService.insert(userDO);
        
        log.debug("userDO : {}, newID : {}", userDO, newId);
        
        return ResponseMessageUtil.genSuccessResult();
    }
    
}
